package xxx.yyy.zzz.movie;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * https://www.1905.com/mdb/film/xxx/info/
 */
public class MovieInfoProcessor implements PageProcessor {

    private static final Logger log = LoggerFactory.getLogger(MoviePerformerProcessor.class);

    private static final String BASE_URL = "https://www.1905.com/mdb/film/%s/info/";

    private String movieId;
    private String url;

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    public MovieInfoProcessor(String movieId) {
        Objects.requireNonNull(movieId);
        this.movieId = movieId;
        this.url = Strings.formatIfArgs(BASE_URL, movieId);
    }

    @Override
    public void process(Page page) {
        // Get Movie Name
        List<Selectable> list = page.getHtml().css("h1.header-wrapper-h1").nodes();
        for (Selectable selectable : list) {
            String content = selectable.xpath("//h1/text()").get();
            page.putField("id", movieId);
            page.putField("name", content);
            break;
        }


        list = page.getHtml().css("dl.fl").nodes();
//        List<Selectable> list = page.getHtml().css("div.infos-conts-top").nodes();

        for (Selectable selectable : list) {
            /*
            if (isNameSection(selectable)) {
                page.putField("name", getPerformer(selectable).get(0));
            } else */
            if (isScoreSection(selectable)) {
                page.putField("score", getPerformer(selectable).get(0));
            } else if (isCountrySection(selectable)) {
                page.putField("countries", getPerformer(selectable));
            } else if (isTypeSection(selectable)) {
                page.putField("types", getPerformer(selectable));
            }
        }
    }

    public Site getSite() {
        return site;
    }

    public String getUrl() {
        Objects.requireNonNull(url);
        return url;
    }

    private boolean isNameSection(Selectable selectable) {
        Objects.requireNonNull(selectable);
//        System.out.println(selectable);

        List<Selectable> list = selectable.css("dt").nodes();
        if (list.size() == 0)
            return false;

        for (Selectable s : list) {
            String content = s.xpath("//dt/text()").get();
            if (content.contains("片") && content.contains("名")) {
                return true;
            }
        }

        return false;
    }

    private boolean isScoreSection(Selectable selectable) {
        Objects.requireNonNull(selectable);

        List<Selectable> list = selectable.css("dt").nodes();
        if (list.size() == 0)
            return false;

        for (Selectable s : list) {
            String content = s.xpath("//dt/text()").get();
            if ("用户评分".equals(content))
                return true;
        }

        return false;
    }

    private boolean isCountrySection(Selectable selectable) {
        Objects.requireNonNull(selectable);

        List<Selectable> list = selectable.css("dt").nodes();
        if (list.size() == 0)
            return false;

        for (Selectable s : list) {
            String content = s.xpath("//dt/text()").get();
            if (content != null
                    && StringUtils.contains(content, "国")
                    && StringUtils.contains(content, "别"))
                return true;
        }

        return false;
    }

    private boolean isTypeSection(Selectable selectable) {
        Objects.requireNonNull(selectable);
        List<Selectable> list = selectable.css("dt").nodes();
        if (list.size() == 0)
            return false;

        for (Selectable s : list) {
            String content = s.xpath("//dt/text()").get().trim();
            if ("影片类型".equals(content))
                return true;
        }

        return false;
    }

    private List<String> getPerformer(Selectable selectable) {
        ArrayList<String> performers = new ArrayList<>(2);
        List<Selectable> list = selectable.css("dd").nodes();

        for (Selectable s : list) {
            String content = s.xpath("//dd/text()").get();
            // Ascii 值为 160 的空格，这种是无法通过replace或者trim处理。需要特殊处理。
            content = content.replaceAll("\\u00A0", " ");
            for (String token : StringUtils.split(content, " ")) {
                performers.add(StringUtils.trim(token));
            }
        }

        return performers;
    }

    /*
    public static void main(String[] args) {
        MovieInfoProcessor processor = new MovieInfoProcessor(2244288);
        Spider.create(processor)
                .addUrl(processor.getUrl())
                .thread(1)
                .run();
    }
     */
}
